﻿using DataMonitor_IBLL;
using DataMonitorMysql.MappingClass;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Memory;
using System.Reflection;

namespace DataMonitorWebApi.Controllers
{
    [Route("[controller]/[action]")]
    [ApiController]
    public class Admin_PropsController : ControllerBase
    {
        private readonly ILogger<Admin_PropsController> _logger;
        private readonly IBLL_Admin _bLL_Props_Admin;
        private readonly string controllerName;
        private readonly IMemoryCache _memoryCache;//内存缓存
        public Admin_PropsController(ILogger<Admin_PropsController> logger, IBLL_Admin bLL_Props_Admin, IMemoryCache memoryCache)
        {
            _logger = logger;
            _bLL_Props_Admin = bLL_Props_Admin;
            _memoryCache = memoryCache;
            controllerName = this.GetType().Name;
        }

        [HttpGet]
        public IActionResult GetPropsAdmin(int page, int pagesize)
        {
            var data = _bLL_Props_Admin.LoadEntities(a => true);
            var datacount = data.Count();
            var pagedata = data.Skip((page - 1) * pagesize).Take(pagesize).OrderBy(a => a.key);
            return Ok(new { pagedata, total = datacount });
        }

        /// <summary>
        /// 编辑公共参数方法
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        [HttpPut]
        public IActionResult EditPropsAdmin([FromBody] dm_props_admin row)
        {
            var t = MethodBase.GetCurrentMethod();
            string? methodName = t?.Name;
            var iseditsucess = _bLL_Props_Admin.EditEntity(row);
            _memoryCache.Remove("datamonitoradminpara");
            if (iseditsucess)
            {
                _logger.LogInformation($"{controllerName}控制器{methodName}方法,执行成功：{DateTime.Now}");
                _memoryCache.Remove("adminprops");//一旦公共参数发生改变则删除内存值
                return Ok("编辑成功");
            }
            else
            {
                _logger.LogError($"{controllerName}控制器{methodName}方法,执行失败-数据库操作失败：{DateTime.Now}");

                return BadRequest("编辑失败");
            }
        }
    }
}
